package lib

//link to 123 309
func init() {
	Probs = append(Probs, Problem{
		Num:         188,
		Discription: "最多k笔股票买卖最大收益",
		Level:       3,
		Labels: map[string]int{
			"动态规划":  1,
			"有限状态机": 1,
		},
	})
}

func MaxProfit4(k int, prices []int) int {
	hold := make([]int, k)
	sold := make([]int, k)
	//要初始化每一个hold[j]，表示前面都不进行交易，直接在第j笔交易时买入
	for j := 0; j < k; j++ {
		hold[j] = -prices[0]
	}

	for i := 1; i < len(prices); i++ {
		hold[0] = max(hold[0], -prices[i])
		sold[0] = max(sold[0], hold[0]+prices[i])
		for j := 1; j < k; j++ {
			hold[j] = max(hold[j], sold[j-1]-prices[i])
			sold[j] = max(sold[j], hold[j]+prices[i])
		}
	}

	return sold[k-1]
}
